<?php
/**
 * Created by PhpStorm.
 * User: tao
 * Date: 10/26/2017
 * Time: 12:38 PM
 */

class RegionController extends  Controller
{
    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page'=>array(
                'class'=>'CViewAction',
            ),
        );
    }
    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            //'postOnly + delete', // we only allow deletion via POST request
        );
    }
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array(
                'allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array(
                    'index',
                    'index2',
                    'index3',
                    'index4',
                    'spider',
                    'demo1',
                    'url',
                ),
                'users'=>array('*'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    public function actionIndex() {
        $conn = Yii::app()->db;
        $url = 'https://d.jd.com/area/get?fid=0&callback=jQuery4786467&_=1508992240741';
        $http = new HttpUtil();
        $str = $http->get($url);
        $area = json_decode($this->dostr($str),true);
        $sql = "insert into tbl_area(uid, name) VALUES ('0','中国'),";
        for ($i = 0; $i < count($area); $i++) {
            if($i<=231) {
                continue;
            }
            $sql .= " ('".$area[$i]['id']."','".$area[$i]['name']."'),";
        }
        $sql = substr($sql, 0, -1).';';
        $num = $conn->createCommand($sql)->execute();
        if($num) {
            echo 'success:'.$num;
        } else {
            echo 'failed';
        }
        unset($conn);
    }
    public function actionIndex2() {
        $http = new HttpUtil();
        $conn = Yii::app()->db;
        $sql = "select * from tbl_area where parent_id = 1 and level = 1 order by id asc";
        $rs = $conn->createCommand($sql)->queryAll();
        foreach ($rs as $v) {
            $url = "https://d.jd.com/area/get?fid=".$v['uid']."&callback=jQuery4786467&_=1508992240741";
            $str = $http->get($url);
            $area = json_decode($this->dostr($str),true);
            $sql = "insert into tbl_area(uid, name, parent_id, level) VALUES ";
            for ($i = 0; $i < count($area); $i++) {
                $sql .= " ('".$area[$i]['id']."','".$area[$i]['name']."','".$v['id']."','2'),";
            }
            $sql = substr($sql, 0, -1).';';
            $num = $conn->createCommand($sql)->execute();
            if($num) {
                echo $v['name'].'=success:'.$num.'<br/>';
            } else {
                echo $v['name'].'=failed'.'<br/>';
            }
        }
        unset($conn);
    }
    public function actionIndex3() {
        $http = new HttpUtil();
        $conn = Yii::app()->db;
        $sql = "select * from tbl_area where level = 2 order by id asc";
        $rs = $conn->createCommand($sql)->queryAll();
        foreach ($rs as $v) {
            $url = "https://d.jd.com/area/get?fid=".$v['uid']."&callback=jQuery4786467&_=1508992240741";
            $str = $http->get($url);
            $area = json_decode($this->dostr($str),true);
            $sql = "insert into tbl_area(uid, name, parent_id, level) VALUES ";
            for ($i = 0; $i < count($area); $i++) {
                $sql .= " ('".$area[$i]['id']."','".$area[$i]['name']."','".$v['id']."','3'),";
            }
            $sql = substr($sql, 0, -1).';';
            $num = $conn->createCommand($sql)->execute();
            if($num) {
                echo $v['name'].'=success:'.$num.'<br/>';
            } else {
                echo $v['name'].'=failed'.'<br/>';
            }
        }
        unset($conn);
    }
    public function actionIndex4() {
        $http = new HttpUtil();
        $conn = Yii::app()->db;
        $sql = "select * from tbl_area where level = 3 order by id asc";
        $rs = $conn->createCommand($sql)->queryAll();
        $sum = 0;
        foreach ($rs as $v) {
            $url = "https://d.jd.com/area/get?fid=".$v['uid']."&callback=jQuery4786467&_=1508992240741";
            $str = $http->get($url);
            $area = json_decode($this->dostr($str),true);
            if(count($area)>0) {
                $sql = "insert into tbl_area(uid, name, parent_id, level) VALUES ";
                for ($i = 0; $i < count($area); $i++) {
                    $sql .= " ('".$area[$i]['id']."','".$area[$i]['name']."','".$v['id']."','4'),";
                }
                $sql = substr($sql, 0, -1).';';
                $num = $conn->createCommand($sql)->execute();
                if($num) {
                    $sum += $num;
                    echo $v['name'].'=success:'.$num.'<br/>';
                } else {
                    echo $v['name'].'=failed'.'<br/>';
                }
            }
        }
        unset($conn);
    }

    public function actionSpider() {
        header("Content-type: text/html; charset=gb2312");
        $url = "http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/index.html";
        $snoopy = new Snoopy;
        $snoopy->fetch($url); //获取所有内容
        //$snoopy->fetchtext($url); //获取文本内容（去掉html代码）
        //$snoopy->fetchlinks($url); //获取链接
        //$snoopy->fetchform($url);  //获取表单
        $txt = $snoopy->results; //显示结果
        //$txt = "<td><a href='12.html'>天津市<br/></a></td><td><a href='13.html'>河北省<br/></a></td>";
        $pattern = '/<td><a href=\'([^<>]+)\.html\'>([^<>]+)<br\/><\/a><\/td>/';


        //preg_match('/<ul class=\"sep\">\s*<li>[\w\W]*align=\"absmiddle\" class=\"rank\" \/><\/a><\/li>/',$html,$result);
        //preg_match_all('/<div\sid=\"([a-z0-9_]+)\">([^<>]+)<\/div>/',$html,$result);
        $arr = array();
        preg_match_all($pattern,$txt,$arr);
        $this->out($arr);
    }


    public function actionDemo1() {
        $conn = Yii::app()->db;
        $sql = "select * from tbl_region where parent_code = '440100' order by region_id asc";
        $rs = $conn->createCommand($sql)->queryAll();

        foreach ($rs as $v) {
            $r = new Street();
            $r->street_code = substr($v['region_code'], 4);
            $r->street_name = $v['region_name'];
            $r->is_show = 0;
            $r->save();
            $sql = "select * from tbl_region where parent_code = '".$v['region_code']."' order by region_id asc";
            $rs1 = $conn->createCommand($sql)->queryAll();
            foreach ($rs1 as $v1) {
                $r1 = new Street();
                $r1->street_code = substr($v1['region_code'], 4);
                $r1->street_name = $v1['region_name'];
                $r1->is_show = 0;
                $r1->save();
                $sql = "select * from tbl_region where parent_code = '".$v1['region_code']."' order by region_id asc";
                $rs2 = $conn->createCommand($sql)->queryAll();
                foreach ($rs2 as $v2) {
                    $r2 = new Street();
                    $r2->street_code = substr($v2['region_code'], 4);
                    $r2->street_name = $v2['region_name'];
                    $r2->is_show = 0;
                    $r2->save();
                    echo "1<br/>";
                }

            }

        }

        unset($conn);
    }





    /*public function actionUrl(){
        $go = new WebCrawler('http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2016/index.html');
        echo $go->getcharset();
        //var_dump($go->getwebinfo());
    }*/

    private function dostr($str){
        if(strlen($str)<15) {
            return $str;
        } else {
            //$str = substr($str, 13);
            $str = substr($str, 14, -1);
            return $str;
        }
    }

    private function out($array) {
        echo '<pre>';
        print_r($array);
        echo '</pre>';
    }

}